﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SharpShare.Storage;
using SharpShare.Diagnostics;
using SharpShare.Storage.Security;

namespace SharpShare.Afp.Protocol.Handlers {
    internal class AfpDeleteRequestHandler : IAfpRequestHandler {
        #region IAfpRequestHandler Members

        public byte CommandCode {
            get { return 8; }
        }

        public AfpResultCode Process(IAfpSession session, DsiHeader dsiHeader, AfpStream requestStream, AfpStream responseStream) {
            requestStream.ReadPadding();

            ushort volumeId = requestStream.ReadUInt16();
            uint directoryId = requestStream.ReadUInt32();
            IAfpVolume volume;

            IStorageItem node = requestStream.ReadPathAndFind(session, volumeId, directoryId, out volume).DemandExists();

            if (node.Parent != null) {
                node.Parent.GetEffectiveAccess(session).DemandRight(StorageAccessRight.DeleteChild);
            }

            node.GetEffectiveAccess(session).DemandRight(StorageAccessRight.Delete);

            string deletedIdentifier = node.ToString();

            node.Delete();

            volume.InvalidateNode(node);

            Log.Add(session, EntryType.Debug, "Session '{0}' deleted storage item '{1}'.", session, deletedIdentifier);

            return AfpResultCode.FPNoErr;
        }

        #endregion
    }
}
